package com.jet.chat.dbquery;

import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.jet.chat.message.Message;

public class ChatQueryAddHistory extends ChatQueryAbstract {

	@Override
	protected ChatQueryResult main(Connection conn, ChatQueryParams chatQueryParams) {
		int senderId = ((ChatQueryAddHistoryParams) chatQueryParams).getSenderId();
		int receiverId = ((ChatQueryAddHistoryParams) chatQueryParams).getReceiverId();
		String channelName = ((ChatQueryAddHistoryParams) chatQueryParams).getChannelName();
		Message message = ((ChatQueryAddHistoryParams) chatQueryParams).getMessage();
		
		Reader reader = new StringReader(message.getContent());
		Statement stmt;
		PreparedStatement ps;
		
		try {
//			Statement stmt = conn.createStatement();
//			ResultSet results = stmt.executeQuery("select max(id) from history");
//			int id = 0;
//			while(results.next()) {
//				id = results.getInt(1);
//			}
//			id = id + 1;
//			results.close();
//			stmt.close();
//			
//			PreparedStatement ps = conn.prepareStatement("insert into history (id, senderid, receiverid, channelname, content) values (?, ?, ?, ?, ?)");
//			ps.setInt(1, id);
//			ps.setInt(2, senderId);
//			ps.setInt(3, receiverId);
//			ps.setString(4, channelName);
//			ps.setClob(5, reader);
//			ps.execute();
//			conn.commit();
			
			stmt = conn.createStatement();
			ResultSet results = stmt.executeQuery("select max(id) from messages");
			int id = 0;
			while(results.next()) {
				id = results.getInt(1);
			}
			id = id + 1;
			results.close();
			stmt.close();
			
			ps = conn.prepareStatement("insert into messages (id, timestamp, senderid, channelname, pub, content) values (?, ?, ?, ?, ?, ?)");
			ps.setInt(1, id);
			ps.setTimestamp(2, message.getTimestamp());
			ps.setInt(3, senderId);
			ps.setString(4, channelName);
			ps.setInt(5, message.getPub());
			ps.setClob(6, reader);
			ps.execute();
			
			message.setId(id);
			
			if (receiverId == 0) {
				ps = conn.prepareStatement("insert into isread (messageid, userid, isread) select " + id + ", id, 0 from users");
				ps.execute();
			} else {
				ps = conn.prepareStatement("insert into isread (messageid, userid, isread) values (?, ?, ?)");
				ps.setInt(1, id);
				ps.setInt(2, receiverId);
				ps.setInt(3, 0);
				ps.execute();
			}
			
			conn.commit();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

}
